package com.ant.storage.controller;

import cn.hutool.json.JSONObject;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.ant.storage.pojo.Dictionary;
import com.ant.storage.utils.LocalJsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author hzd
 * @version 1.0
 * @date 2022/4/8 13:52
 */
@RestController
@RequestMapping("/easyExcel")
@Api(tags = "EasyExcel导入导出测试")
public class EasyExcelController {

    @SneakyThrows(IOException.class)
    @ApiOperation(value = "导出会员列表Excel")
    @RequestMapping(value = "/exportMemberList", method = RequestMethod.GET)
    public void exportMemberList(HttpServletResponse response) throws IOException {
        setExcelRespProp(response, "数据字典");//LocalJsonUtil
        List<Dictionary> memberList = LocalJsonUtil.getListFromJson("json/members.json", Dictionary.class);
        EasyExcel.write(response.getOutputStream())
                .head(Dictionary.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("数据字典")
                .doWrite(memberList);
    }
    /**
     * 设置excel下载响应头属性
     */
    private void setExcelRespProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }


}
